package com.example.orderconsumer.consumer;

import com.example.orderconsumer.bean.Order;
import com.example.orderconsumer.dao.OrderDao;
import lombok.SneakyThrows;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author DELL
 * @ClassName OrderConsumer
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/7/6
 * @Version 1.0.0
 */
@Component
@RocketMQMessageListener(consumerGroup = "delay-order-consumer-01",topic = "delay-order")
public class DelayConsumer implements RocketMQListener<String>{


    public static final String LOCK_STOCK_LUA=  "local counter = redis.call('hget',KEYS[1],ARGV[1]); \n" +
            "local result  = counter - ARGV[2];" +
            "   redis.call('hset',KEYS[1],ARGV[1],result);\n" +
            "local presell = redis.call('hget',KEYS[1],ARGV[3]); \n" +
            "local resultpre  = presell + ARGV[2];" +
            "if(resultpre>=0 ) then \n" +
            "   redis.call('hincrby',KEYS[1],ARGV[3],ARGV[2]);\n" +
            "   return 1;\n" +
            "end;\n" +
            "return 0;\n";

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate redisTemplate;


//
//    @SneakyThrows
//    @Override
//    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
//        for (MessageExt messageExt : list) {
//            String orderNo = new String(messageExt.getBody(), "utf-8");
//            Order order = new Order();
//            order.setOrderNo(orderNo);
//            Optional<Order> one = orderDao.findOne(Example.of(order));
//            if(one.isPresent()){
//                System.out.println("订单不存在");
//               continue;
//            }
//
//            DefaultRedisScript<Long> stringRedisScript = new DefaultRedisScript<>();
//            stringRedisScript.setScriptText(LOCK_STOCK_LUA);
//            stringRedisScript.setResultType(Long.class);
//
//            RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
//
//            //定义key
//            List<String> keyList = new ArrayList<String>();
//            keyList.add("ORDER-STOCK");
//            Long restult = (Long)redisTemplate.execute(stringRedisScript,stringRedisSerializer,
//                    stringRedisSerializer,keyList,"RESIDUE-STOCK",-1,"PRESELL-STOCK");
//
//            if(restult.equals(0)){
//                System.out.println("库存回滚失败！");
//               throw new Exception("库存回滚失败");
//            }
//            Order order1 = one.get();
//            //待付款
//            if(order1.getStatus().equals(1)){
//                //超时
//                order1.setStatus(3);
//            }
//            orderDao.saveAndFlush(order1);
//
//        }
//
//        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//    }

    @Override
    public void onMessage(String orderNo) {

        Order order = new Order();
        order.setOrderNo(orderNo);
        Optional<Order> one = orderDao.findOne(Example.of(order));
        if(!one.isPresent()){
            System.out.println("订单不存在");
            return;
        }

        DefaultRedisScript<Long> stringRedisScript = new DefaultRedisScript<>();
        stringRedisScript.setScriptText(LOCK_STOCK_LUA);
        stringRedisScript.setResultType(Long.class);

        RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();

        //定义key
        List<String> keyList = new ArrayList<String>();
        keyList.add("ORDER-STOCK");
        Long restult = (Long)redisTemplate.execute(stringRedisScript,stringRedisSerializer,
                stringRedisSerializer,keyList,"RESIDUE-STOCK","-1","PRESELL-STOCK");

        if(restult.equals(0)){
            System.out.println("库存回滚失败！");
        }
        Order order1 = one.get();
        //待付款
        if(order1.getStatus().equals(1)){
            //超时
            order1.setStatus(3);
        }
        System.out.println("订单超时,回滚库存成功");
        orderDao.saveAndFlush(order1);

    }
}
